﻿using HualongExcel.Utilities;
using System;
using System.Windows.Forms;

namespace HualongExcel.Froms
{
    public partial class MappingForm : Form
    {
        private static MappingForm formIns;

        public static MappingForm FormIns
        {
            get
            {

                if (formIns == null || formIns.IsDisposed)
                    formIns = new MappingForm();
                return formIns;
            }
        }

        public static void ShowSignleForm(bool isDialogue)
        {

            if (isDialogue)
                FormIns.ShowDialog();
            else
                FormIns.Show();

        }
        public static void ShowSignleForm(bool isDialogue, string originCell_Address, string targetCell_Address)
        {

            FormIns.originCell_Address = originCell_Address;
            FormIns.targetCell_Address = targetCell_Address;
            ShowSignleForm(isDialogue);
        }


        public static void HideSignleForm()
        {
            FormIns.Hide();
        }

        public static void DisposeSignleForm()
        {
            FormIns.Dispose();
        }


        private string originCell_Address;
        private string targetCell_Address;

        public static Action<string, string> confirmCallback;

        public MappingForm()
        {
            InitializeComponent();
        }

        private void targetCellTextBox_DoubleClick(object sender, EventArgs e)
        {
            //获取当前选中的单元格，填入targetCellTextBox
            targetCellTextBox.Text = Common.CurrentExcelApp.ActiveCell.Address;
        }

        private void originCellTextBox_DoubleClick(object sender, EventArgs e)
        {
            //获取当前选中的单元格，填入originCellTextBox
            originCellTextBox.Text = Common.CurrentExcelApp.ActiveCell.Address;
        }

        private void confirmButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(originCellTextBox.Text) || string.IsNullOrEmpty(targetCellTextBox.Text))
            {

                MessageBox.Show("添加映射失败，目标或者原始单元格地址为空");
                return;
            }
            confirmCallback?.Invoke(originCellTextBox.Text, targetCellTextBox.Text);
            HideSignleForm();
        }

        private void MappingForm_Load(object sender, EventArgs e)
        {
            this.Left = Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;//桌面的宽度的一半减去自身宽的的一半
            this.Top = Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2;//桌面的高度的一半减去自身高度的一半

            this.originCellTextBox.Text = originCell_Address;
            this.targetCellTextBox.Text = targetCell_Address;
        }

        private void originCellTextBox_TextChanged(object sender, EventArgs e)
        {
            PreviewTextBox.Text = originCellTextBox.Text.ReplaceVariable();
        }
    }
}
